package com.st.util;

import com.st.po.WeChatPayRequest;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @version V 1.0
 * @auther ROG
 * @date 2024/10/24
 * @project_name back
 * @description
 */
@Component
public class WeChatPayUtil {
    @Value("${wechat.app-id}")
    private String appId;

    @Value("${wechat.mch-id}")
    private String mchId;

    @Value("${wechat.api-key}")
    private String apiKey;

    @Value("${wechat.notify-url}")
    private String notifyUrl;

    private static final String UNIFIED_ORDER_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder";

    public Map<String, String> createOrder(WeChatPayRequest payRequest) throws Exception {
        Map<String, String> params = new HashMap<>();
        params.put("appid", appId);
        params.put("mch_id", mchId);
        params.put("nonce_str", WXPayUtil.generateNonceStr());
        params.put("body", payRequest.getBody());
        params.put("out_trade_no", payRequest.getOutTradeNo());
        params.put("total_fee", String.valueOf(payRequest.getTotalFee()));
        params.put("spbill_create_ip", payRequest.getSpbillCreateIp());
        params.put("notify_url", notifyUrl);
        params.put("trade_type", "JSAPI");
        params.put("openid", payRequest.getOpenId());

        // 签名处理
        String sign = WXPayUtil.generateSignature(params, apiKey);
        params.put("sign", sign);

        // 发送请求
        String xmlData = WXPayUtil.mapToXml(params);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(UNIFIED_ORDER_URL);
        httpPost.setEntity(new StringEntity(xmlData, "UTF-8"));
        httpPost.setHeader("Content-Type", "application/xml");

        CloseableHttpResponse response = httpClient.execute(httpPost);
        String responseXml = EntityUtils.toString(response.getEntity(), "UTF-8");

        // 解析微信支付返回的XML
        Map<String, String> resultMap = WXPayUtil.xmlToMap(responseXml);

        if ("SUCCESS".equals(resultMap.get("return_code")) && "SUCCESS".equals(resultMap.get("result_code"))) {
            // 返回给前端支付需要的参数
            Map<String, String> payMap = new HashMap<>();
            payMap.put("appId", appId);
            payMap.put("nonceStr", WXPayUtil.generateNonceStr());
            payMap.put("package", "prepay_id=" + resultMap.get("prepay_id"));
            payMap.put("signType", "MD5");
            payMap.put("timeStamp", String.valueOf(System.currentTimeMillis() / 1000));

            // 生成签名
            payMap.put("paySign", WXPayUtil.generateSignature(payMap, apiKey));
            return payMap;
        } else {
            throw new Exception("微信支付下单失败：" + resultMap.get("return_msg"));
        }

    }
}
